package com.study.controller;


import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class LoginController {
	@RequestMapping(value="/login") 
	public String login(Model model,  String name,  String password) {
//		 model.addAttribute("test", "点击完成");
//		 return "views/indexTest";

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(name, password);
		try {
			subject.login(token);
//			Session session = subject.getSession();
//			session.setAttribute("subject", subject);
			model.addAttribute("flag", subject.getPrincipal());
			return "index";

		} catch (AuthenticationException e) {
			model.addAttribute("error", "验证失败");
			return "login";
		}
	}
	@RequestMapping("/toLogin")
	public String toLogin() {
//		 model.addAttribute("test", "点击完成");
//		 return "views/indexTest";
		return "login";
	}
	
	@RequestMapping(value = "/logout")
	public String logout(RedirectAttributes  attr,HttpServletRequest request) {
		SecurityUtils.getSubject().logout();
		request.getSession().invalidate();
		attr.addFlashAttribute("message","您已安全退出系统");
		return "index";
	}

}
